import Entry from '../Entry';
import Accrual from '../Accrual';

import {Cask} from 'cascadium';

export const accrual = (accrual, dir, {cr=0, dr=0}={}) => {
  if (accrual instanceof Accrual) {
    return accrual.copy();
  } else switch (dir) {
    case '贷':
    case 'Cr':
    case 'cr':
      return new Accrual({cr: accrual, dr: 0});
    case '借':
    case 'Dr':
    case 'dr':
      return new Accrual({dr: accrual, cr: 0});
    default:
      return new Accrual({cr, dr});
  }
}

class Category extends Entry {
  constructor({opening, closing, openingDir, closingDir, openingDr, openingCr, closingDr, closingCr, ...entry}={}, opts) {
    super(entry, opts);

    this.opening = accrual(opening, openingDir, {cr: openingCr, dr:openingDr});
    this.closing = accrual(closing, closingDir, {cr: closingCr, dr:closingDr});

  }

  static from(list, {orderKey}={}) {

    if (list.some(entry => !(entry instanceof Category))) {
      throw Error(`Category.from: 新的余额项目必须由Category列表累加而成，但是发现了 [${list.find(entry => !(entry instanceof Category)).constructor.name}] 对象`);
    }

    if (list.some(({curr:{code}}, i, a) => code !== a[0].curr.code)) {
      throw Error('Category.from: 试图将不同的科目累加到一起');
    }

    const cask = new Cask(...list);

    const cate = new Category(cask[0], {emptyAccrual: true});

    if (orderKey !== undefined) {
      cask.orderBy(orderKey);
    }

    for (let entry of cask) {
      cate.add(entry, {isAccum: true});
    }

    return cate;
  }


  add(entry, {isAccum=false}={}) {

    if (!isAccum){
      this.opening.add(entry.opening);
    }
    
    this.accrual.add(entry.accrual);

    if(isAccum) {
      this.closing = entry.closing.copy();
    } else {
      this.closing.add(entry.closing);
    }
  }


  copy() {
    return new Category(this);
  }
}

export default Category;